package com.hero.herocat;

import com.hero.servlet.HeroRequest;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;

/**
 * @author linhui
 */
public class HttpCustomRequest implements HeroRequest {

    private HttpRequest httpRequest;

    public HttpCustomRequest(HttpRequest httpRequest) {
        if (httpRequest == null) {
            throw new InvalidParameterException("HttpRequest can not null");
        }
        this.httpRequest = httpRequest;
    }

    public String getPathName(){
        /// 获取到路径的最后一段名字
        String pathName = "";
        if (getUri().contains("/")) {
            pathName = getUri().substring(getUri().lastIndexOf("/")+ 1) ;
        }

        if (pathName.contains("?")) {
            pathName = pathName.substring(0, pathName.indexOf("?"));
        }
        return pathName;

    }


    @Override
    public String getUri() {
        return httpRequest.uri();
    }

    @Override
    public String getPath() {
        QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri());
        return decoder.path();
    }

    @Override
    public String getMethod() {
        return httpRequest.method().name();
    }

    @Override
    public Map<String, List<String>> getParameters() {
        QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri());
        return decoder.parameters();
    }

    @Override
    public List<String> getParameters(String name) {
        Map<String, List<String>> parameters = getParameters();
        if (parameters == null) {
            return null;
        }
        return parameters.get(name);
    }

    @Override
    public String getParameter(String name) {
        List<String> parameters = getParameters(name);
        if (parameters == null || parameters.size() == 0) {
            return null;
        }
        return parameters.get(0);
    }
}
